package com.example.eeuse;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import java.util.*;

public class KibanaCacheDump {
    public static void main(String[] args) throws Exception {
        //查询的日期
        String dateStr="2023-11-06";
        File file=new File("D:\\test\\"+dateStr+".txt");
        BufferedWriter bufferedWriter=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true), "utf-8"));
        //账号
        String username="elastic";
        //密码
        String password="monitor*2020";
        //组装密码
        String credentials = username+":"+password;
        String encodeCredentials = Base64.encode(credentials,Charset.forName("utf-8"));

        //连接
        String url="http://10.81.96.48:5601/api/console/proxy?path=%2Fshopping_log_cache_update-*%2F_search&method=GET";

        //请求头
        String allHeaderStr = "kbn-version: 8.5.1\n" +
                "x-kbn-context: %7B%22name%22%3A%22dev_tools%22%2C%22url%22%3A%22%2Fapp%2Fdev_tools%22%2C%22type%22%3A%22application%22%2C%22page%22%3A%22console%22%7D";
        String[] headers = allHeaderStr.split("\n");



        Date beginDate=DateUtil.parse(dateStr,"yyyy-MM-dd");
        Calendar searchTime = Calendar.getInstance();
        searchTime.setTime(beginDate);
        searchTime.add(Calendar.HOUR,-8);

        for(int i=0;i<=5760;i++) {
            List<String> line=new ArrayList<>(10000);
            String beginTime=DateUtil.format(searchTime.getTime(), "yyyy-MM-dd'T'HH:mm:ss");
            searchTime.add(Calendar.SECOND, 15);
            String endTime=DateUtil.format(searchTime.getTime(), "yyyy-MM-dd'T'HH:mm:ss");
            //创建post请求
            HttpRequest post = HttpUtil.createPost(url);
            //设置请求头
            for (String header : headers) {
                String[] headerKeyAndValue = header.split(": ");
                post.header(headerKeyAndValue[0], headerKeyAndValue[1]);
            }
            //设置认证信息
            post.header("Authorization", "Basic " + encodeCredentials);

            String body = "{\n" +
                    "    \"from\": 0,\n" +
                    "    \"size\": 10000,\n" +
                    "    \"query\": {\n" +
                    "        \"bool\": {\n" +
                    "            \"boost\": 1.0,\n" +
                    "            \"must\": [\n" +
                    "              {\"range\":{\n" +
                    "                \"@timestamp\":{\n" +
                    "                  \"gte\":\""+beginTime+"\",\n" +
                    "                  \"lt\":\""+endTime+"\"\n" +
                    "                }\n" +
                    "              }\n" +
                    "              }\n" +
                    "            ]\n" +
                    "        }\n" +
                    "    }\n" +
                    "}";
            //设置请求体
            post.body(body);
            //请求
            HttpResponse execute = post.execute();
            //获得响应结果
            String json = execute.body();
//            System.out.println(json);
            //转成map
            Map map = JSONUtil.toBean(json, Map.class);
            int total=(int)((Map)((Map)map.get("hits")).get("total")).get("value");
            if(total>0)
            {
                List<Map> itemList=(List<Map>)((Map)map.get("hits")).get("hits");
                for(Map item:itemList)
                {
                   Map object= (Map) item.get("_source");
                   String traceId=(String) object.get("TRACE_ID");
                    String timestamp=(String) object.get("@timestamp");
                    String cacheKey=(String) object.get("CACHE_KEY");
                    String expireTime=(String) object.get("EXPIRE_TIME");
                    String _id=(String) item.get("_id");
                    line.add(timestamp.replace("T"," ").replace("Z","")+" "+traceId+",LOG_CACHE_UPDATE,"+expireTime+","+_id+","+cacheKey);
                }
                writeLine(bufferedWriter,line);
                //FileUtil.appendLines(line,file,"utf-8");
                System.out.println(beginTime+","+line.size());
                line.clear();
            }

        }


    }

    public  static void  writeLine(BufferedWriter bufferedWriter,List<String> list) throws Exception {
        for (String str:list) {
            bufferedWriter.write(str);
            bufferedWriter.newLine();
        }
        bufferedWriter.flush();
    }
}
